const {
  app,
  BrowserWindow,
  ipcMain,
  Notification,
  nativeTheme,
  Menu,
  Tray,
  shell,
} = require('electron')
const path = require('path')

// 托盘对象
let appTray = null
// 是否可以退出
let trayClose = false

function showNotification(msg) {
  const notification = new Notification(msg)
  notification.show()
}

const createSwitchTheme = () => {
  ipcMain.handle('setTheme', async (event, themeName) => {
    nativeTheme.themeSource = themeName
  })
  ipcMain.handle(
    'showNotification',
    async (event, msg) => await showNotification(msg),
  )
}

const createWindow = () => {
  const mainWindow = new BrowserWindow({
    title: '旅记点滴-可视化-拖拽生成vue项目',
    icon: path.join(__dirname, '../public/favicon.ico'),
    height: 600,
    minHeight: 600,
    width: 800,
    minWidth: 800,
    // 是否允许用户缩放窗口大小
    useContentSize: true,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule: true,
      preload: path.join(__dirname, 'preload.js'),
      contextIsolation: true,
    },
    // 是否使用浏览器外形
    frame: true,
    // 是否隐藏菜单栏
    autoHideMenuBar: false,
    transparent: false,
  })
  // 动态切换主题
  createSwitchTheme()

  if (app.isPackaged) {
    mainWindow.loadURL(`file://${path.join(__dirname, '../dist/index.html')}`)
  } else {
    mainWindow.loadURL('http://localhost:8284')
    mainWindow.webContents.openDevTools({ mode: 'bottom' })
  }

  mainWindow.on('close', (event) => {
    if (!trayClose) {
      // 最小化
      mainWindow.hide()
      event.preventDefault()
    }
  })
  mainWindow.on('closed', () => {
    trayClose = true
    app.quit()
  })
  //防止闪烁，让画面准备好了再显示
  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
  })
  // 系统托盘右键菜单
  const trayMenuTemplate = [
    {
      label: '百度一下',
      click: function () {
        // 打开外部链接
        shell.openExternal('https://www.baidu.com')
      },
    },
    {
      label: '退出',
      click: function () {
        // 退出
        trayClose = true
        app.quit()
      },
    },
  ]
  // 系统托盘图标
  const iconPath = path.join(__dirname, '../public/favicon.ico')
  appTray = new Tray(iconPath)
  // 图标的上上下文
  const contextMenu = Menu.buildFromTemplate(trayMenuTemplate)
  // 设置此托盘图标的悬停提示内容
  appTray.setToolTip('旅记点滴')
  // 设置此图标的上下文菜单
  appTray.setContextMenu(contextMenu)
  // 主窗口显示隐藏切换
  appTray.on('click', () => {
    mainWindow.isVisible() ? mainWindow.hide() : mainWindow.show()
  })
}

app.whenReady().then(() => {
  createWindow()

  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})
